package com.chatbot.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.chatbot.entity.Character;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class TTSService {
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Value("${tts.api.key}")
    private String apiKey;
    
    @Value("${tts.api.url}")
    private String apiUrl;
    
    @Value("${tts.audio.base-url}")
    private String audioBaseUrl;

    /**
     * 生成语音文件，适配Qwen-TTS
     * @param text 要转换的文本
     * @param character 角色信息
     * @return 生成的音频文件URL
     */
    public String generateSpeech(String text, Character character) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            // Qwen-TTS请求体
            Map<String, Object> input = new HashMap<>();
            input.put("text", text);

            Map<String, Object> parameters = new HashMap<>();
            if (StringUtils.hasText(character.getVoiceId())) {
                parameters.put("voice", character.getVoiceId());
            }
            // 解析voiceSettings JSON
            if (StringUtils.hasText(character.getVoiceSettings())) {
                Map<String, Object> voiceSettings = objectMapper.readValue(character.getVoiceSettings(), Map.class);
                parameters.putAll(voiceSettings);
            } else {
                setDefaultVoiceSettings(parameters, character);
            }

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-tts");
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);

            // 打印实际请求体内容和 headers
            System.out.println("[TTS] Request Body: " + objectMapper.writeValueAsString(requestBody));
            System.out.println("[TTS] Request Headers: " + headers);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, request, Map.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Object audioUrlObj = response.getBody().get("audio_url");
                if (audioUrlObj != null) {
                    return audioUrlObj.toString();
                }
                Object audioDataObj = response.getBody().get("audio_data");
                if (audioDataObj != null) {
                    return "data:audio/wav;base64," + audioDataObj.toString();
                }
            }
            throw new RuntimeException("Qwen-TTS生成语音失败");
        } catch (Exception e) {
            throw new RuntimeException("Qwen-TTS调用异常: " + e.getMessage());
        }
    }

    /**
     * 根据角色特征设置默认的语音参数（参数名需与Qwen-TTS一致）
     */
    private void setDefaultVoiceSettings(Map<String, Object> parameters, Character character) {
        // 根据角色年龄设置音调
        if (character.getAge() != null) {
            if (character.getAge() < 18) {
                parameters.put("pitch", 1.2); // 年轻声音，较高音调
            } else if (character.getAge() > 50) {
                parameters.put("pitch", 0.8); // 年长声音，较低音调
            }
        }

        // 根据性格设置语速
        if (character.getPersonality() != null) {
            String personality = character.getPersonality().toLowerCase();
            if (personality.contains("活泼") || personality.contains("开朗")) {
                parameters.put("speed", 1.2); // 快速语速
            } else if (personality.contains("稳重") || personality.contains("沉静")) {
                parameters.put("speed", 0.9); // 较慢语速
            }
        }

        // 根据语言风格设置情感
        if (character.getLanguageStyle() != null) {
            String style = character.getLanguageStyle().toLowerCase();
            if (style.contains("热情")) {
                parameters.put("emotion", "happy");
            } else if (style.contains("严肃")) {
                parameters.put("emotion", "serious");
            }
        }

        // 设置默认值
        parameters.putIfAbsent("pitch", 1.0);
        parameters.putIfAbsent("speed", 1.0);
        parameters.putIfAbsent("volume", 1.0);
    }
} 